<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryList">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExport">导出</el-button>
        </el-form-item>

        <el-form-item label="" prop="resource">
          <el-col :span="12">
            <el-upload
                class="upload-demo"
                action="http://localhost:8080/department/importExcel"
                list-type="picture">
              <el-button  type="primary">点击导入</el-button>
            </el-upload>
          </el-col>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="部门编号" width="150"  sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="150" sortable>
      </el-table-column>
      <!--:formatter="formatSex"-->
      <el-table-column prop="state" label="启用状态" width="150" sortable>
        <template scope="scope"><!--scope有整行数据-->
          <div v-if="scope.row.state == 0" slot="reference" class="name-wrapper">
            <el-tag type="danger" size="medium">禁用</el-tag>
          </div>
          <div v-if="scope.row.state == 1" slot="reference" class="name-wrapper">
            <el-tag type="success" size="medium">启用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="150" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="150" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-size="pageSize"
          :page-sizes="pageSizes"
          :current-page="currentPage"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门编号"  prop="sn">
          <el-input v-model="editForm.sn" placeholder="请输入部门编号" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入部门名称" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员" prop="manager_id">
          <el-select v-model="editForm.managerId" placeholder="请选择管理员">
            <!--
            key是唯一的用于去重 必须填
            label显示的值
            value提交到v-model的值与manager_id绑定
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <!--
            checkStrictly: true表示单选
            :options="departmentTree" 数据来源

          -->
          <el-cascader v-model="editForm.parentId"
                       :options="departmentTree"
                       :props="{
                         checkStrictly: true,
                         label:'name',
                         value:'id'
                       }"
                       clearable>
          </el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
			  //标题
			  title:'',
        //关键字查询
				filters: {
          keyword: '',
          sn:'',
          state:''
				},
        //部门树
        departmentTree:'',
        //部门列表
				departments: [],
        //员工数据
				employees: [],
        //分页条件
        pageSizes:[5, 10, 15, 30],
        total: 0,
        currentPage: 1,
        pageSize:10,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
        //输入提示
        editFormRules: {
          name: [
            //required必传标记 信息  trigger：失去焦点触发
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
        },
				//编辑界面数据
				editForm: {
          id:null,
          sn: '',
          name: '',
          dirPath: -1,
          state: 0,
          managerId:null,
          parentId:null
				},
			}
		},
		methods: {
      //导出文件
      handleExport(){
        location.href = "http://localhost:8080/department/export";
      },
      handleSizeChange(val){
        this.pageSize = val;
				this.getDepartments();

      },
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
      queryList(){
        this.currentPage = 1;
        this.getDepartments();
      },
			//获取用户列表
			getDepartments() {
				let para = {
					currentPage: this.currentPage,
          pageSize: this.pageSize,
          sn: this.filters.sn,
          keyword: this.filters.keyword,
          state: this.filters.state
				};
				this.listLoading = true;
        //获取部门列表数据
        this.$http.post("/department/pageList",para).then(res =>{
          console.log(res)
          this.departments = res.data.data;
          this.total = res.data.total;
          this.listLoading = false;//关闭忙等
				});
			},
      //获取员工列表
      getEmployees(){
        this.$http.get("/employee/list").then(res => {
          this.employees =res.data;
        })
      },
      getDepartmentTree(){
        this.$http.get("/department/tree").then(res =>{
          this.departmentTree = res.data;
        })
      },
			//删除
			handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '温馨提示', {
          type: 'error'//提示图标
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/department/"+row.id).then(res =>{
            this.listLoading = false;
            //判断是否删除成功
            if(res.data.success){
              //弹出提示框
              this.$message({
                message:res.data.msg,
                type:'success',
              })
              //跳转第一页
              this.currentPage = 1;
              //刷新列表
              this.getDepartments();
            }else {
              //删除失败
              this.$message({
                message:res.data.msg,
                type:'warning',
              })
            }
          })
        });
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        //重置表单验证
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields();//重置表单验证
        }
        this.title ='编辑'
        this.editForm = Object.assign({}, row);//克隆数据
        this.editFormVisible = true; //是否显示
			},
			//显示新增界面
			handleAdd: function () {
        //重置表单验证
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields();//重置表单验证
        }
        this.title ='新增'
        //置空表单
        this.editForm = {
          id:null,
          sn:'',
          name:'',
          state:0,
          managerId:'',
          parentId:''
        }
        this.editFormVisible =true;
			},
			//编辑
			editSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
              this.editLoading = true;
              //克隆表单数据
              let para = Object.assign({}, this.editForm);
              //parent_id存在进入
              if(para.parentId){
                //是否为对象
                console.log(typeof para.parentId)
                if(typeof para.parentId == 'object'){
                  //将数组转换成数字
                  para.parentId = para.parentId[para.parentId.length - 1];
                }
              }
              this.$http.put("/department",para).then(res =>{
                if(res.data.success){
                  //关闭忙等
                  this.editLoading = false;
                  this.$message({
                    message:res.data.msg,
                    type:'success'
                  })
                  //重置表单验证
                  this.$refs['editForm'].resetFields();
                  this.editFormVisible = false;//关闭模态框
                  this.getDepartments();//刷新列表
                }else {
                  this.$message({
                    message:res.data.msg,
                    type:'warning'
                  })
                  this.editLoading =false;//忙等关闭
                }
              })
            });
          }
        });
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        //返回一个id数组
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;//开启忙等
          this.$http.patch("/department/del", ids).then(res =>{
            this.listLoading = false;
            //判断是否删除成功
            if(res.data.success){
              //弹出提示框
              this.$message({
                message:res.data.msg,
                type:'success',
              })
              //跳转第一页
              this.currentPage = 1;
              //刷新列表
              this.getDepartments();
            }else {
              //删除失败
              this.$message({
                message:res.data.msg,
                type:'warning',
              })
            }
          })
        });
			}
		},
		mounted() {
			this.getDepartments();
			this.getEmployees();
			this.getDepartmentTree();
		}
	}

</script>

<style scoped>

</style>